package com.teachoa.web;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.teachoa.bean.Dict;
import com.teachoa.util.IDUtil;

public class DictController extends BaseController {

	public void index() {
		renderJsp("dict.jsp");
	}
	
	public void tree() {
		renderJson(JSON.toJSONString(Dict.dao.getDictTree()));
	}
	
	public void load() {
		Dict dict = Dict.dao.findById(getPara());
		renderJson(JsonKit.toJson(dict));
	}
	
	@Before(Tx.class)
	public void del() {
		String id = getPara(0);
		String pid = getPara(1);
		try {
			int size = Dict.dao.getSonSizeByPid(pid);
			if(size==1)
				Dict.dao.findById(pid).set("is_leaf", 1).update();
			Dict.dao.deleteById(id);
			
			renderJson(success("删除成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("删除失败！！"));
		}
	}
	
	@Before(Tx.class)
	public void save() {
		Dict dict = getModel(Dict.class);
		String id = dict.getStr("id");
		String pid = dict.getStr("pid");
		try {
			if(StringUtils.isBlank(id)) {
				dict.set("id", IDUtil.getId());
				Dict parent = Dict.dao.findById(pid);
				int isLeaf = parent.getInt("is_leaf");
				if(isLeaf==1) {
					parent.set("is_leaf", 0).update();
				}
				dict.set("is_leaf", 1).save();
			} else {
				dict.update();
			}
			renderJson(success("保存成功！！"));
		} catch (Exception e) {
			e.printStackTrace();
			renderJson(fail("保存失败！！"));
		}
	}

}
